#define __LIBRARY__
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/sem.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/mm.h>

_syscall2(sem_t *,sem_open,const char *,name,unsigned int,value)
_syscall1(int,sem_wait,sem_t *,sem)
_syscall1(int,sem_post,sem_t *,sem)
_syscall1(int,sem_unlink,const char *,name)
_syscall3(int,shmget,key_t,key,size_t,size,int,shmflg);
_syscall3(void *,shmat,int,shmid,const void *,shmaddr,int,shmflg);

#define BUFSIZE 10      
#define PRODUCTS 500 
#define INVAILD_NUMBER  -1 
const int key = 1190202209;
const char *full_name = "lab6full";
const char *empty_name = "lab6empty";
const char *mutex_name = "lab6mutex";
sem_t *empty, *full, *mutex;
int shmid;
void Producer()
{
    int i,fd, num = 0;
    int *buf,*p;
    buf = (int *)shmat(shmid,NULL,0);
    while (num <= PRODUCTS)
    {
        sem_wait(empty);
        sem_wait(mutex);
        p = buf;
        while(*p!= INVAILD_NUMBER && p< buf + BUFSIZE)
            p++;
        *p=num;
        sem_post(mutex);
        sem_post(full);
        num++;
        /*sleep(10);*/
    }
    return;
}

int main()
{
    sem_unlink(full_name);
    sem_unlink(empty_name);
    sem_unlink(mutex_name);
    empty = sem_open(empty_name, BUFSIZE); 
    full = sem_open(full_name, 0);         
    mutex = sem_open(mutex_name, 1);       
    shmid = shmget(key, BUFSIZE*sizeof(int),0);
    memset(shmat(shmid,NULL,0),-1,BUFSIZE*sizeof(int));
    Producer();
    return 0;
}
